package net.oschina.git.hikoyan.helloapi.async.flowcontrol;

import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by yan on 17/2/20.
 */
public class QPSFlowControl {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    public FlowControlResult doQPSFlowControl(String flowControlKey) {
        RateLimiter rateLimiter = FlowControlMap.getQpsDataMap().get(flowControlKey);

        if (rateLimiter != null) {
            boolean qpsResult = false;
            try {
                qpsResult = rateLimiter.tryAcquire(100L, TimeUnit.MILLISECONDS);
                logger.info("QPSFlowControl  : ",String.valueOf(qpsResult));
            } catch (Exception e) {
                e.printStackTrace();
                return FlowControlResult.QPS_EXCEPTION;//$NON-NLS-QPS限流异常$
            }

            if (!qpsResult) {
                return FlowControlResult.QPS_OVERFLOW;//$NON-NLS-QPS流控溢出$
            }
        }
        return FlowControlResult.FC_OK;//$NON-NLS-执行成功$
    }
}
